package com.leyou.trade.mq;

import com.leyou.auth.utils.UserContext;
import com.leyou.common.constants.MQConstants;
import com.leyou.trade.service.CartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class TradeListener {

    @Autowired
    private CartService cartService;

    //下单完成后购物车清除
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MQConstants.QueueConstants.TRADE_GOODS_QUEUE, durable = "true"),
            exchange = @Exchange(name = MQConstants.ExchangeConstants.TRADE_GOODS_NAME, type = ExchangeTypes.TOPIC),
            key = MQConstants.RoutingKeyConstants.TRADE_GOODS_KEY
    ))
    public void listenTradeGoods(Map<String,Object> deleteMap){

        if (!CollectionUtils.isEmpty(deleteMap)) {
            List<Integer> idList = (List<Integer>) deleteMap.get("skuIds");
            Integer userId = (Integer) deleteMap.get("userId");
            // 下单完成后购物车清除
            for (Integer skuId : idList) {
                String id = String.format("u%ds%d", userId, skuId);
                log.info("下单成功需要清理的sku:" + id);
                cartService.deleteCartById(id);
            }
        }
    }
}
